const Koa = require('koa')
const http = require('http');
const WebSocket = require('ws');

const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

const server = http.createServer(app.callback());
const wss = new WebSocket.Server({ server });



// 引入WebSocket路由处理函数
const { handleWebSocketMessage } = require('./Controller/websocket');

// 引入WebSocket路由
const websocketRouter = require('./routes/websocket');

// 引入RealtimeData模型
const { RealtimeData } = require('./models/RealtimeData');


// WebSocket连接建立时的处理
wss.on('connection', (ws) => {
  console.log('WebSocket connection established');

  // 处理WebSocket消息
  ws.on('message', (message) => {
    handleWebSocketMessage(ws, message);
  });

  // WebSocket连接关闭时的处理
  ws.on('close', () => {
    console.log('WebSocket connection closed');
  });
});





// 引入身份验证路由
const auth = require('./routes/auth')

const {sequelize} = require('./config/db')
const cors = require('@koa/cors');

app.use(cors());

// 错误处理
onerror(app)



// 中间件
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// 日志记录
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// 路由

app.use(auth.routes(), auth.allowedMethods())

// 错误处理
app.on('error', (err, ctx) => {
  console.error('服务器错误', err, ctx)
});





// 将WebSocket路由挂载到指定前缀
app.use(websocketRouter.routes(), websocketRouter.allowedMethods());

// 启动HTTP服务器
server.listen(3001, () => {
  console.log('Server started on http://localhost:3000');
});


// 进行数据库连接验证
sequelize.authenticate().then(()=>{
  console.log('连接成功');
}).catch(err=>{
  console.error('连接失败');
})

module.exports = app